<?php
/**
 * WebSocket API接口
 * 
 * 用于发送消息到WebSocket服务器
 */

// 加载通用文件
require_once __DIR__ . '/../common/autoload.php';

// 检查是否已安装
if (!file_exists(__DIR__ . '/../.installed') && basename($_SERVER['PHP_SELF']) !== 'install.php') {
    header('Location: /install.php');
    exit;
}

// 检查AJAX请求
if (!isset($_SERVER['HTTP_X_REQUESTED_WITH']) || strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !== 'xmlhttprequest') {
    header('HTTP/1.1 403 Forbidden');
    echo json_encode(['success' => false, 'message' => '禁止直接访问']);
    exit;
}

// 检查登录状态
check_login();

// 加载WebSocket客户端
require_once __DIR__ . '/../vendor/autoload.php';
use App\WebSocketClient;

// 获取请求方法
$method = $_SERVER['REQUEST_METHOD'];

// 响应数据
$response = [
    'success' => false,
    'message' => '无效请求'
];

// 处理POST请求
if ($method === 'POST') {
    // 获取请求体JSON数据
    $json = file_get_contents('php://input');
    $data = json_decode($json, true);
    
    if ($data) {
        $action = $data['action'] ?? '';
        
        // 创建WebSocket客户端
        $client = new WebSocketClient();
        
        switch ($action) {
            case 'send_new_order':
                // 发送新订单通知
                if (isset($data['order']) && is_array($data['order'])) {
                    $result = $client->sendNewOrder($data['order']);
                    $response = [
                        'success' => $result,
                        'message' => $result ? '订单通知已发送' : '发送失败'
                    ];
                } else {
                    $response = [
                        'success' => false,
                        'message' => '缺少订单数据'
                    ];
                }
                break;
                
            case 'update_order_status':
                // 更新订单状态
                if (isset($data['order']) && is_array($data['order'])) {
                    $result = $client->sendOrderStatusUpdate($data['order']);
                    $response = [
                        'success' => $result,
                        'message' => $result ? '状态更新已发送' : '发送失败'
                    ];
                } else {
                    $response = [
                        'success' => false,
                        'message' => '缺少订单数据'
                    ];
                }
                break;
                
            default:
                $response = [
                    'success' => false,
                    'message' => '未知操作'
                ];
                break;
        }
    } else {
        $response = [
            'success' => false,
            'message' => '无效的JSON数据'
        ];
    }
}

// 返回JSON响应
header('Content-Type: application/json');
echo json_encode($response); 